package com.zto.sch.base.thread;

import lombok.Data;

/**
 * @program: sch-diy-parent
 * @description:
 * @author: sch
 * @create: 2021-01-09 23:40
 **/
public class ThreadDemo_ODDEVEN {
    @Data
    static class Resourse {
        private Integer count;

        public Resourse(Integer count) {
            this.count = count;
        }
    }

    static class ThreadPrintOdd implements Runnable {
        private Resourse resourse;

        public ThreadPrintOdd(Resourse resourse) {
            this.resourse = resourse;
        }

        @Override
        public void run() {
            try {
                while (resourse.getCount() < 100) {
                    synchronized (resourse) {
                        Integer count = resourse.getCount();
                        if (resourse.getCount() % 2 != 0) {
                            System.out.println(Thread.currentThread().getName() + "--->" + count);
                            resourse.setCount(++count);
                            resourse.notify();
                        } else {
                            resourse.wait();
                        }
                    }
                }
            } catch (Exception e) {

            }
        }
    }

    static class ThreadPrintEven implements Runnable {
        private Resourse resourse;

        public ThreadPrintEven(Resourse resourse) {
            this.resourse = resourse;
        }

        @Override
        public void run() {
            try {
                while (resourse.getCount() < 100) {
                    synchronized (resourse) {
                        Integer count = resourse.getCount();
                        if (resourse.getCount() % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + "======>" + count);
                            resourse.setCount(++count);
                            resourse.notify();
                        } else {
                            resourse.wait();
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    public static void main(String[] args) {
        Resourse resourse = new Resourse(1);
        ThreadPrintOdd threadPrintOdd = new ThreadPrintOdd(resourse);
        ThreadPrintEven threadPrintEven = new ThreadPrintEven(resourse);

        Thread t1 = new Thread(threadPrintOdd);
        Thread t2 = new Thread(threadPrintEven);

        t1.start();
        t2.start();
    }
}